package com.jm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jm.common.util.entity.R;
import com.jm.common.util.entity.SelectCondition;
import com.jm.pojo.Category;
import com.jm.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<IPage<Category>> selectByPage(SelectCondition condition) {
        IPage<Category> categoryIPage = categoryService.selectByPageCondition(condition);
        return R.success(categoryIPage);
    }

    /**
     * 添加分类
     */
    @PostMapping()
    public R<String> addOne(@RequestBody Category category) {
        boolean save = categoryService.save(category);
        if (save) return R.success("添加成功");
        return R.error("添加失败");
    }

    /**
     * 删除分类
     */
    @DeleteMapping
    public R<String> removeOne(String ids) {
//        检查该分类对象对应的分类是否有数据
        boolean result1 = categoryService.checkId(ids);
        if (result1) return R.error("该分类不为空,删除失败");
//        若是该分类下没有东西则则进行分类删除
        boolean result2 = categoryService.removeById(ids);
        if (result2) return R.success("删除成功");
        return R.error("删除失败");
    }

    /**
     * 修改分类
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        boolean b = categoryService.updateById(category);
        if (b) return R.success("修改成功");
        return R.error("修改失败");
    }

    /**
     * 根据分类的类型获得对应数据列表(单品/套餐)
     */
    @GetMapping("/list")
    public R<List<Category>> getListByCategoryType(SelectCondition selectCondition) {
        List<Category> categoryByType = categoryService.getDataListByType(selectCondition.getType());
        return R.success(categoryByType);
    }
}
